package archivemanagement;

import static com.google.common.base.Throwables.propagate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;

import metagrammar.Operator;
import metagrammar.OperatorDescription;

import com.google.inject.Inject;

public class OperatorDescriptionManager implements
ArchiveManager<Operator, OperatorDescription> {
    
    private final ArrayList<OperatorDescriptionArchive> libraries;
    
    @Inject
    private OperatorDescriptionManager(
            OperatorDescriptionArchive... operatorDescriptionLibraries)
    {
        libraries = new ArrayList<OperatorDescriptionArchive>(
                Arrays.asList(operatorDescriptionLibraries));
    }
    
    @Override
    public OperatorDescription load(Operator key)
    {
        for(OperatorDescriptionArchive lib : libraries) {
            OperatorDescription description;
            try {
                description = lib.loadDescription(key);
                if(description != null) {
                    return description;
                }
            }
            catch(IOException e) {
                propagate(e);
            }
        }
        return null;
    }
    
    @Override
    public void add(OperatorDescription value)
    {
        for(OperatorDescriptionArchive lib : libraries) {
            try {
                lib.writeDescription(value);
            }
            catch(IOException e) {
                propagate(e);
            }
        }
    }
    
    @Override
    public int update(OperatorDescription value)
    {
        int updatedLibraries = 0;
        for(OperatorDescriptionArchive lib : libraries) {
            try {
                if(lib.containsDescription(value.getOperator())) {
                    lib.writeDescription(value);
                    updatedLibraries++;
                }
            }
            catch(IOException e) {
                propagate(e);
            }
        }
        return updatedLibraries;
    }
    
    @Override
    public Collection<OperatorDescription> loadAll()
    {
        ArrayList<OperatorDescription> operators = new ArrayList<OperatorDescription>();
        for(OperatorDescriptionArchive lib : libraries) {
            try {
                operators.addAll(lib.loadAllDescriptions());
            }
            catch(IOException e) {
                throw propagate(e);
            }
        }
        return operators;
    }
}